from rest_framework import serializers

from goods.models import SKU

# 保存购物车序列化器和修改
class CartSerializer(serializers.Serializer):
    # id count selected
    sku_id = serializers.IntegerField(label='sku id ', min_value=1)
    count = serializers.IntegerField(label='数量', min_value=1)
    selected = serializers.BooleanField(label='是否勾选', default=True)

    # 对字段进行额外的验证
    def validate(self, attrs):
        # 查询数据库判断商品是否存在
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except Exception as e:
            raise serializers.ValidationError('商品不存在')
        # 判断购买数量是否大于库存
        if sku.stock < attrs['count']:
            raise serializers.ValidationError('商品库存不足')

        return attrs


# 查询购物车序列化器
class CartSKUSerializer(serializers.ModelSerializer):
    """
    购物车商品数据序列化器
    """
    count = serializers.IntegerField(label='数量')
    selected = serializers.BooleanField(label='是否勾选')

    class Meta:
        model = SKU
        fields = ('id', 'count', 'name', 'default_image_url', 'price', 'selected')


# 删除购物车序列化器
class CartDeleteSerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(label='商品id', min_value=1)

    def varializer_sku_id(self, value):
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        return value


# 购物车全选序列化器
class CartSelectAllSerializer(serializers.Serializer):
    selected = serializers.BooleanField(label='全选')